package com.nowcoder.community.service;

import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.utils.CommunityConstant;
import com.nowcoder.community.utils.CommunityUtil;
import com.nowcoder.community.utils.MailClient;
import com.nowcoder.community.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    //现在redis中看看缓存有没有
    public User findUserById(int id) {
        //return userMapper.selectUserById(id);
        User user = getCache(id);
        if (user == null){
            user = initCache(id);
        }
        return user;
    }

    /**
     * 用户注册服务
     *
     * @return
     */
    public Map<String, Object> register(User user) {
        //存储返回的结果
        Map<String, Object> map = new HashMap<>();
        //1.先判断传入的user是否为null
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        //2.判断user的属性是否空,username,password,email
        if (user.getUsername() == null) {
            //结果存入map 然后直接返回
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (user.getPassword() == null) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (user.getEmail() == null) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        //3.处理账号的数据，看是否存在用户名和邮箱重复
        User u = userMapper.selectUserByName(user.getUsername());
        if (u != null) {
            //存在重复用户名
            map.put("usernameMsg", "该账号已存在");
            return map;
        }

        u = userMapper.selectUserByEmail(user.getEmail());
        if (u != null) {
            //存在重复邮箱
            map.put("emailMsg", "该账号已存在");
            return map;
        }

        //4.数据合法，构建对象，并向用户发送激活码邮件\
        //password,salt type status activationCode headerUrl createTime
        //设置长度为5的随机盐
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        //根据随机盐重新组装密码,在MD5加密
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        //设置状态：未激活
        user.setStatus(0);
        user.setType(0);
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        //激活码，直接用UUID
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setCreateTime(new Date());
        //插入用户
        userMapper.insertUser(user);

        //向用户发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8080/community/activation/111/act_code
        // Mybatis id自增，在插入用户后，会回填自增的id (所以这里不设置也能得到id)
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);

        String content = templateEngine.process("/mail/activation", context);

        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }

    /**
     * 根据用户id和激活码来更改数据库中用户状态
     *
     * @param userId
     * @param code
     * @return
     */

    public int activation(int userId, String code) {
        User user = userMapper.selectUserById(userId);
        System.out.println(user);
        //判断用户状态
        if (user.getStatus() == 1) {
            //重复激活
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            //激活成功
            userMapper.updateStatus(userId, 1);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * @param username
     * @param password
     * @param expiredSeconds 过期时间
     * @return 处理结果（失败）（成功 和 登录凭证）
     */
    public Map<String, Object> login(String username, String password, long expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        //空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }

        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        //验证账号
        User user = userMapper.selectUserByName(username);

        //账号是否存在
        if (user == null) {
            map.put("usernameMsg", "账号不存在！");
            return map;
        }

        //账号是否未激活
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "账号未激活！");
            return map;
        }

        //验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确！");
            return map;
        }

        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        String uuid = CommunityUtil.generateUUID();
        System.out.println(uuid);
        loginTicket.setTicket(uuid);
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        //插入数据库
        //loginTicketMapper.insertLoginTicket(loginTicket);

        //用缓存做
        String ticketKey = RedisUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey,loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    public void logout(String ticket) {
        //loginTicketMapper.updateStatus(ticket, 1);
        String ticketKey = RedisUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }

    /**
     * 向目标邮箱发送验证码
     *
     * @param email
     */
    public Map<String, Object> sendVerifyCode(String email) {
        //存储业务返回的结果
        Map<String, Object> map = new HashMap<>();
        //校验邮箱
        //1. 判空
        if (StringUtils.isBlank(email)) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        //2. 账号是否存在
        User user = userMapper.selectUserByEmail(email);
        if(user == null){
            map.put("emailMsg", "用户不存在！");
            return map;
        }
        //3.账号是否激活
        if (user.getStatus() == 0) {
            map.put("emailMsg", "账号未激活！");
            return map;
        }
        //邮箱正确，则向邮箱发邮件
        Context context = new Context();
        context.setVariable("email", email);
        //生成六位验证码
        String code = CommunityUtil.random3();
        map.put("verifyCode",code);
        context.setVariable("verifyCode", code);
        String content = templateEngine.process("/mail/forget", context);
        mailClient.sendMail(email,"重置密码验证码", content);

        return map;
    }



    /**
     * 对重置密码，传入的参数进行判断
     *
     * @param email
     * @param password
     * @return
     */
    public Map<String, Object> resetPassword(String email, String password) {
        Map<String, Object> map = new HashMap<>();
        //1.空值判断
        if (StringUtils.isBlank(email)) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "新密码不能为空！");
            return map;
        }

        //2.错误处理
        //验证账号存在
        User user = userMapper.selectUserByEmail(email);
        if (user == null) {
            map.put("emailMsg", "该用户不存在！");
            return map;
        }
        //账号是否激活
        if (user.getStatus() == 0) {
            map.put("emailMsg", "账号未激活！");
            return map;
        }

        //正确，则更改它的密码
        int i = userMapper.updatePassword(user.getId(),CommunityUtil.md5(password + user.getSalt()));
        map.put("updateRows",i);
        return map;
    }

    //查找登录凭证
    public LoginTicket findLoginTicket(String ticket){
        //return loginTicketMapper.selectLoginTicketByTicket(ticket);
        String ticketKey = RedisUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
    }

    public User findUserByName(String name){
        return userMapper.selectUserByName(name);
    }


    public void updateHeaderUrl(int userId,String HeaderUrl){
        userMapper.updateHeader(userId, HeaderUrl);
        clearCache(userId);
    }

    /**
     * 判断user对象中的密码与传入的password是否一致
     * @param user
     * @param password
     * @return
     */
    public boolean testPassword(User user,String password){
        return user.getPassword().equalsIgnoreCase(CommunityUtil.md5(password + user.getSalt()));
    }

    /**
     * 更改用户密码
     * @param userId
     * @param password
     */
    public void updatePassword(int userId,String password){
        userMapper.updatePassword(userId,password);
        clearCache(userId);
    }


    //1.优先从缓存中取
    private User getCache(int userId){
        String key = RedisUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(key);
    }


    //2.取不到时初始化缓存数据
    private User initCache(int userId){
        User user = userMapper.selectUserById(userId);
        String userKey = RedisUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey, user,3600, TimeUnit.SECONDS);
        return user;
    }

    //3.数据变更时清除缓存数据
    private void clearCache(int userId){
        String key = RedisUtil.getUserKey(userId);
        redisTemplate.delete(key);
    }


    public Collection<? extends GrantedAuthority> getAuthorities(int userId){
        User user = userMapper.selectUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1:
                        return AUTHORITY_ADMIN;
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

}
